//
//  HDPhotoViewController.swift
//  图片选择器
//
//  Created by wty on 16/4/21.
//  Copyright © 2016年 wty. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let photoCount = 6

class HDPhotoViewController: UICollectionViewController {
    //记录用户选择的图片
     var photos:[UIImage] = []
    private var  layout = UICollectionViewFlowLayout()
    init(){
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setCollectionView()
    }
    //MARK  collectionView设置
    private func setCollectionView(){
        layout.itemSize = CGSize(width: 80, height: 80)
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        self.collectionView?.contentInset = UIEdgeInsetsMake(30, 10, 10, 10)
        self.collectionView!.registerClass(HDPhotoSelecedCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    // MARK   数组源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //当图片没有到达最大张数时候  就显示图片的和一个加号
        //当图片数量达到最大值时候 就是显示最大张数
        return photos.count < photoCount ? photos.count+1 :photos.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)as! HDPhotoSelecedCell
        
        cell.photoSelectorCellDidClickDeleteButton = { [weak self](cell:HDPhotoSelecedCell)->() in
            //获取cell的indexPath
            let indexPath = collectionView.indexPathForCell(cell)
            //删除图片
            self!.photos.removeAtIndex(indexPath!.item)
            //刷新数据
            collectionView.reloadData()
        }
        cell.photoSelectorCellDidClickAddButton = { [weak self](cell:HDPhotoSelecedCell)->() in
            //系统图片选择器
            let pickerVc = UIImagePickerController()
            pickerVc.delegate = self
            self!.presentViewController(pickerVc, animated: true, completion: nil)
        }
        //给cell赋值
        if indexPath.item < photos.count {
            cell.image = photos[indexPath.item]
        }else{
            cell.setupAddButton()
        }
        return cell
    }
}
//系统图片选择器的代理方法
extension HDPhotoViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //选中系统图片选择器就会调用这个方法 如果调用就需要自己关
    /**
    - parameter picker:      系统图片选择器
    - parameter image:       选择的图片
    - parameter editingInfo: 编辑信息
    */
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //压缩图片 约定宽度为300
        let newWidth:CGFloat = 300
        let oldWidth:CGFloat = image.size.width
        let oldHeight:CGFloat = image.size.height
        let newHeight:CGFloat = newWidth * oldHeight / oldWidth
        //异步绘制图片
        image.hd_AsyncDrawImage(CGSize(width: newWidth, height: newHeight)) { (image) -> () in
            //绘制好的图片添加到数组中
            self.photos.append(image)
            //刷新数据
            self.collectionView?.reloadData()
            //关闭控制器
            picker.dismissViewControllerAnimated(true, completion: nil)
        }
        
    }
}
//设置cell
class HDPhotoSelecedCell : UICollectionViewCell {
   //闭包传递事件
    var photoSelectorCellDidClickAddButton : ((cell:HDPhotoSelecedCell)->())?
    var photoSelectorCellDidClickDeleteButton : ((cell:HDPhotoSelecedCell)->())?
    //属性观察期赋值
    var image :UIImage?{
        didSet{
            //将图片赋值给加号图片
            addButton.setImage(image, forState: UIControlState.Normal)
            //隐藏删除按钮
            deleteButton.hidden = false
        }
    }
    //设置加号按钮
    func setupAddButton (){
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        deleteButton.hidden = true
    }
  //MARK  初始化方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    private func prepareUI(){
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        // VFL
        // 加号按钮, 填充父控件
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: [], metrics: nil, views: ["ab" : addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: [], metrics: nil, views: ["ab" : addButton]))
        
        // 删除按钮, 父控件右上角
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[db]-0-|", options: [], metrics: nil, views: ["db" : deleteButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[db]", options: [], metrics: nil, views: ["db" : deleteButton]))
        
    }
    
    
     //MARK  懒加载控件
    //删除按钮
    private lazy var  deleteButton : UIButton = {
        let  button = UIButton()
        button.setImage(UIImage(named:"compose_photo_close" ), forState: UIControlState.Normal)
        button.addTarget(self, action: Selector("deleteClick"), forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    //加号按钮
    private lazy var addButton : UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        button.addTarget(self, action: Selector("addClick"), forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
   //MARK  按钮监听事件
    @objc private func deleteClick(){
    photoSelectorCellDidClickDeleteButton!(cell:self)
    }
    @objc private func addClick(){
        photoSelectorCellDidClickAddButton!(cell: self)
    }

}
